
import uuid
{{if eq .isUser true}}from datetime import timedelta{{end}}
from redis import Redis
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import insert, delete, text, select, update, desc
from model.{{Lower .structName}} import {{.structName}}
from model import find_pojos, delete_pojo, update_pojo, insert_pojo
from tools.utils import transaction_decorator, {{if eq .isUser true}}analysis_token_decorator, create_access_token, {{end}}transaction_decorator_sync
from datasource.obtains import get_db_session, get_async_session, get_async_redis, get_sync_redis
from model import get_sync_db, SyncSession
from variable import TASK{{if eq .isUser true}}, ACCESS_TOKEN_EXPIRE_MINUTES{{end}}

{{if eq .isUser true}}
async def login(session, userInfo: dict):
    user_id = ""

    try:
        u = (await session.execute(select({{.structName}}).filter({{.structName}}.username == userInfo["username"]))).scalars().first()

        if u == None:
            u = User()
            u.id = uuid.uuid1().__str__()
            u.nickname = userInfo["username"]
            u.username = userInfo["username"]
            u.password = userInfo["password"]
            session.add(u)

            user_id = u.id

        else:
            if userInfo["password"] != u.password:
                return {
                    "message": "密码错误",
                    "code": "400",
                    "data": None
                }

            user_id = u.id

    except Exception as e:
        await session.rollback()
        await session.close()

        return {"message": "数据库操作失败", "code": 500, "errors": e}
    else:
        await session.commit()
    finally:
        await session.close()

    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)

    return {
        "message": "登录成功",
        "code": "200",
        "data": {"token_info": await create_access_token(user_id, expires_delta=access_token_expires)},
    }
{{- end}}

@transaction_decorator
async def add_{{Lower .structName}}(session: AsyncSession, o):
    o["id"] = uuid.uuid1().__str__()
    await insert_pojo(session, {{.structName}}, o)

@transaction_decorator
async def update_{{Lower .structName}}(session: AsyncSession, o):
    await update_pojo(session, {{.structName}}, o)

@transaction_decorator
async def delete_{{Lower .structName}}(session: AsyncSession, id):
    await delete_pojo(session, {{.structName}}, id)

async def find_{{Lower .structName}}_one(session: AsyncSession, id) -> {{.structName}}:
    result = (await session.execute(
        select({{.structName}}).where({{.structName}}.id == id))).scalars().first()

    await session.close()

    return result

async def find_{{Lower .structName}}_all(session: AsyncSession, o) -> list[{{.structName}}]:
    query = select({{.structName}})
    {{$classname := .structName}}
    {{- range .fieldNameList}}
    {{- if eq .isSave true}}
    if o.{{.FieldName}} != "":
        query = query.where({{$classname}}.{{.FieldName}}.like("%" + o.{{.FieldName}} + "%"))
    {{print}}
    {{- end}}
    {{- end}}
    if o.start_time != "":
        query = query.where({{.structName}}.created_at >= o.start_time)

    if o.end_time != "":
        query = query.where({{.structName}}.created_at <= o.end_time)

    pojos = await find_pojos(session, {{.structName}}, query, o)

    await session.close()

    return pojos

def {{Lower .structName}}_task(session: AsyncSession, redis: Redis):
    print("定时任务逻辑 。。。")

TASK.add_job({{Lower .structName}}_task, **{
        "trigger": "interval",
        "hours": 2,
        "jitter": 120
    }, id=uuid.uuid1().__str__(),
    args=[get_sync_db(), get_sync_redis()])

